package org.chen.model.service.impl;

import org.apache.commons.collections.CollectionUtils;
import org.chen.model.domain.Menu;
import org.chen.model.domain.Role;
import org.chen.model.domain.Users;
import org.chen.dto.UserAuthDTO;
import org.chen.model.repository.UsersRepository;
import org.chen.model.service.MenuService;
import org.chen.model.service.RoleService;
import org.chen.model.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 陈亮
 * @Date: 2019/3/24 14:13
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @Override
    public Users findByAccount(String account) {
        return usersRepository.findByAccount(account);
    }

    @Override
    public Users findByAccountAndPassword(String account, String password) {
        return usersRepository.findByAccountAndPassword(account, password);
    }

    @Override
    public List<Users> findAll() {
        return usersRepository.findAll();
    }

    @Override
    public UserAuthDTO AssembleRoleAndPermissionByUser(Integer id, String sessionId) {
        List<Role> roleList = roleService.findRoleByAccountId(id);
        List<Menu> menuList = null;
        if (CollectionUtils.isNotEmpty(roleList)) {
            for (Role r : roleList) {
                menuList = menuService.findByRoleId(r.getId());
            }
        }
        UserAuthDTO userAuthDTO = new UserAuthDTO();
        userAuthDTO.setRoles(roleList);
        userAuthDTO.setMenus(menuList);
        userAuthDTO.setToken(sessionId);
        return userAuthDTO;
    }
}
